package com.rent.appointment.aspect;

import com.rent.appointment.annotation.Perm;
import com.rent.common.exception.BusinessException;
import com.rent.common.interceptor.UserContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Component
@Aspect
public class PermAspect {
    @Pointcut("execution(* com.rent.appointment.controller.*.*(..))")
    public void pointcut(){}

    @Around("pointcut()")
    public Object checkPerm(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Perm permAnnotation = method.getAnnotation(Perm.class);
        if(permAnnotation == null){//该方法不需要权限
            return joinPoint.proceed();//执行目标方法
        }

        //admin 直接放行
        if (2 == UserContext.getRole()){
            return joinPoint.proceed();//执行目标方法
        }

        //检查放行 landlord    user
        Map<Integer,String> map = new HashMap<>();
        map.put(0,"user");
        map.put(1,"landlord");

        String s = map.get(UserContext.getRole());

        if (!s.equals(permAnnotation.value())){
            throw new BusinessException("没有访问权限！");
        }

        return joinPoint.proceed();//执行目标方法
    }
}
